//
//  ImagePicker.swift
//  HYOnline
//
//  Created by zhuxuhong on 2017/6/1.
//  Copyright © 2017年 zhuxuhong. All rights reserved.
//

import UIKit
import Tipper

typealias ImagePickerCallback = ((UIImage?) -> Void)

class ImagePicker: NSObject {
    static let shared = ImagePicker()
    
    fileprivate var callback: ImagePickerCallback?
    
    public func showWith(presentingViewController: UIViewController, sourceType: UIImagePickerControllerSourceType, allowsEditing: Bool = false, completion: ImagePickerCallback?){
        if  sourceType == .camera &&
            !UIImagePickerController.isSourceTypeAvailable(.camera) {
            Tipper.toast(message: "额，你的相机不可用~")
            return
        }
        callback = completion
        
        let picker = UIImagePickerController()
		picker.allowsEditing = allowsEditing
        picker.delegate = self
        picker.sourceType = sourceType
        presentingViewController.present(picker, animated: true, completion: nil)
    }
}

extension ImagePicker: UIImagePickerControllerDelegate, UINavigationControllerDelegate{
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        
        let image = picker.allowsEditing
            ?  info[UIImagePickerControllerEditedImage]
            : info[UIImagePickerControllerOriginalImage]
        picker.dismiss(animated: true) {
            self.callback?(image as? UIImage)
        }
    }
    
    func navigationControllerSupportedInterfaceOrientations(_ navigationController: UINavigationController) -> UIInterfaceOrientationMask {
        return .portrait
    }
}
